package com.valten.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 通过 @ControllerAdvice 和 @ExceptionHandler，可以自定义对全部 Controller 接口的异常处理机制！
 *
 * @className GlobalExceptionHandler
 * @package com.valten.exception
 * @author huangyuanli
 * @date 2020/9/27 14:04
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

   /**-------- 通用异常处理方法 --------**/
   @ExceptionHandler(Exception.class)
   public ResponseEntity<Object> error(Exception e) {
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());    // 通用异常结果
   }

   /**-------- 指定异常处理方法 --------**/
   @ExceptionHandler(NullPointerException.class)
   public ResponseEntity<Map<String, Object>> error(NullPointerException e) {
      e.printStackTrace();
      Map<String, Object> map = new HashMap<>();
      map.put("code", "20007");
      map.put("message", "空指针异常");
      return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(map);
   }

   @ExceptionHandler(IndexOutOfBoundsException.class)
   public ResponseEntity<Map<String, Object>> error(IndexOutOfBoundsException e) {
      e.printStackTrace();
      Map<String, Object> map = new HashMap<>();
      map.put("code", "20008");
      map.put("message", "数组越界");
      return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(map);
   }

   /**-------- 自定义定异常处理方法 --------**/
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException e) {
      return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
   }
}

